import request from "@/utils/request";
import { Loading, Message } from "element-ui";
import { v4 as uuidv4 } from "uuid";
import store from "@/store";
export function fammterString(type, uuid, label = "course") {
  let resString;
  let dirName = uuid ? uuid : uuidv4();
  //1.正式课程   2.草稿   3.考试文件    type类型1，2，3
  let typeObj = {
    1: "form@lFile",
    2: "dr@ftFile",
    3: "ex@mFile",
  };
  if (label == "course"||label == "knowledge") {
    resString = `${process.env.VUE_APP_BASE_LOGINPLATFORM}/${label}/${dirName}/${typeObj[type]}`;
  } else {
    resString = `${process.env.VUE_APP_BASE_LOGINPLATFORM}//${label}/${dirName}`;
  }

  return resString;
}
// 获取oss签名
export function getOssSignature(path) {
  return request({
    url: "/common/getOssSignature",
    method: "get",
    params: {
      path: path,
    },
  });
}
let that = this;
// 上传到oss
export function uploadOSS(files, path, needName, event) {
  return new Promise((resolve, reject) => {
    var loading = Loading.service({
      lock: true,
      text: `正在上传,请稍等…(0%)`,
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.6)",
    });
    var fileListCopy;
    var filesReturn;
    var dirPath;
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, "0");
    const day = String(currentDate.getDate()).padStart(2, "0");

    const formattedDate = `${year}/${month}/${day}`;

    // 如果是数组
    if (files instanceof FileList) {
      fileListCopy = Array.from(files);
    }
    // 如果不是数组
    else {
      fileListCopy = [files];
    }
    filesReturn = [];
    let sum = 0;
    fileListCopy.forEach((file) => {
      console.log(file);
      const fileSize = file.size / 1024 / 1024; // 转换为MB
      if (fileSize > 1024) {
        loading.close();
        Message({
          message: `文件大小不能超过1GB,请用《格式工厂》压缩！`,
          type: "warning",
        });
        if (event.target.value) {
          event.target.value = "";
        }
        return;
      }
      if (path) {
        dirPath = path;
      } else {
        dirPath = `${process.env.VUE_APP_BASE_LOGINPLATFORM}/${file.name
          .split(".")
          .pop()
          .toLowerCase()}/${formattedDate}`;
      }
      console.log("dirPath", dirPath);
      getOssSignature(dirPath).then((res) => {
        let expire = new Date().getTime();
        let formData = new FormData();
        formData.append(
          "key",
          `${dirPath}/${expire}.${file.name.split(".").pop()}`
        );
        formData.append("OSSAccessKeyId", res.data.accessId);
        formData.append("policy", res.data.policy);
        formData.append("Signature", res.data.signature);
        formData.append("success_action_status", 200); // 成功后返回的操作码
        formData.append("file", file);
        request({
          url: res.data.host,
          method: "post",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          onUploadProgress(e) {
            if (e.lengthComputable) {
              let p =
                e.loaded / e.total == 1
                  ? "99"
                  : parseInt((e.loaded / e.total) * 100);
              loading.setText(`正在上传,请稍等…(${p}%)`);
            }
          },
          withCredentials: false,
          data: formData,
        })
          .then((response) => {
            if (needName) {
              filesReturn.push({
                name: file.name,
                url: `${res.data.url.replace(
                  "https://hgcc-metaxun.oss-cn-hangzhou.aliyuncs.com",
                  "https://oss.metaxun.com"
                )}/${expire}.${file.name.split(".").pop()}`,
              });
            } else {
              filesReturn.push(
                `${res.data.url.replace(
                  "https://hgcc-metaxun.oss-cn-hangzhou.aliyuncs.com",
                  "https://oss.metaxun.com"
                )}/${expire}.${file.name.split(".").pop()}`
              );
            }

            sum++;
            if (sum == fileListCopy.length) {
              loading.setText(`正在上传,请稍等…(100%)`);
              loading.close();
              resolve(filesReturn);
            }
          })
          .catch((err) => {
            loading.close();
          });
      });
    });
  });
}

export function upload(data) {
  return new Promise((resolve, reject) => {
    const loading = Loading.service({
      lock: true,
      text: `正在上传,请稍等…(0%)`,
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.6)",
    });
    request({
      url: "/common/upload",
      method: "post",
      data: data,
      onUploadProgress(e) {
        if (e.lengthComputable) {
          let p =
            e.loaded / e.total == 1
              ? "99"
              : parseInt((e.loaded / e.total) * 100);
          loading.setText(`正在上传,请稍等…(${p}%)`);
        }
      },
    })
      .then((res) => {
        loading.setText(`正在上传,请稍等…(100%)`);
        loading.close();
        resolve(res);
      })
      .catch((err) => {
        loading.close();
        reject(err);
      });
  });
}
export function uploadInCourse(data) {
  return new Promise((resolve, reject) => {
    const loading = Loading.service({
      lock: true,
      text: `正在上传,请稍等…(0%)`,
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.6)",
    });
    request({
      url: "/common/uploadInCourse",
      method: "post",
      data: data,
      onUploadProgress(e) {
        if (e.lengthComputable) {
          let p =
            e.loaded / e.total == 1
              ? "99"
              : parseInt((e.loaded / e.total) * 100);
          loading.setText(`正在上传,请稍等…(${p}%)`);
        }
      },
    })
      .then((res) => {
        loading.setText(`正在上传,请稍等…(100%)`);
        loading.close();
        resolve(res);
      })
      .catch((err) => {
        loading.close();
        reject(err);
      });
  });
}

export function uploadsInCourse(data) {
  return new Promise((resolve, reject) => {
    const loading = Loading.service({
      lock: true,
      text: `正在上传,请稍等…(0%)`,
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.6)",
    });
    request({
      url: "/common/uploadsInCourse",
      method: "post",
      data: data,
      onUploadProgress(e) {
        if (e.lengthComputable) {
          let p =
            e.loaded / e.total == 1
              ? "99"
              : parseInt((e.loaded / e.total) * 100);
          loading.setText(`正在上传,请稍等…(${p}%)`);
        }
      },
    })
      .then((res) => {
        loading.setText(`正在上传,请稍等…(100%)`);
        loading.close();
        resolve(res);
      })
      .catch((err) => {
        loading.close();
        reject(err);
      });
  });
}
